package com.hjrpc.babyyamall.authserver.web;

import com.google.gson.Gson;
import com.hjrpc.babyyamall.authserver.feign.MemberFeignService;
import com.hjrpc.common.dto.LoginUserTo;
import com.hjrpc.common.dto.SocialUser;
import com.hjrpc.common.utils.HttpUtils;
import com.hjrpc.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
@Slf4j
public class OAuth2Controller {

    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) {
        // 根据code换取accessToken
        Map<String, String> bodys = new HashMap<>();
        bodys.put("client_id", "116285787");
        bodys.put("client_secret", "e0ba58230a857252a98df13c8f73104a");
        bodys.put("grant_type", "authorization_code");
        bodys.put("redirect_uri", "http://auth.babyyamall.com/oauth2.0/weibo/success");
        bodys.put("code", code);
        try {
            HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token",
                    null, new HashMap<>(), null, bodys);
            if (response.getStatusLine().getStatusCode() == 200) {
                Gson gson = new Gson();
                SocialUser socialUser = gson.fromJson(EntityUtils.toString(response.getEntity()), SocialUser.class);
                // 如果尚未注册会自动注册
                R r = memberFeignService.login(socialUser);
                if (r.isSuccess()) {
                    LoginUserTo loginUser = r.getData(LoginUserTo.class);
                    log.info("返回的数据：{}", loginUser);
                    session.setAttribute("loginUser",loginUser);
                    // 登录成功返回首页
                    return "redirect:http://babyyamall.com";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return "redirect:http://auth.babyyamall.com/login.html";
    }
}
